package com.mmall.common;

import com.mmall.Exception.ParamException;
import com.mmall.Exception.PermissionException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 全局异常处理
 * Created by pc on 2019/3/22.
 */

@Slf4j
public class SpringExceptionResolve implements HandlerExceptionResolver {
    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object o, Exception ex) {
        String url = request.getRequestURL().toString();
        ModelAndView mv;
        String defaultMsg = "System error";
        //页面请求 后缀.page  之外请求为 .json
        if(url.endsWith(".json")){
            if(ex instanceof PermissionException || ex instanceof ParamException){
                JsonData result = JsonData.fial(ex.getMessage());
                mv = new ModelAndView("jsonView",result.toMap());
            }else{
                log.error("unknown json exception url:"+url ,ex);
                JsonData result = JsonData.fial(defaultMsg);
                mv = new ModelAndView("jsonView",result.toMap());
            }
        }else if(url.endsWith(".page")){
            // 返回页面错误
            log.error("unknown page exception url:"+url ,ex);
            JsonData result = JsonData.fial(defaultMsg);
            mv = new ModelAndView("exception",result.toMap());
        } else {
            log.error("unknown json exception url:"+url ,ex);
            JsonData result = JsonData.fial(defaultMsg);
            mv = new ModelAndView("jsonView",result.toMap());
        }
        return mv;
    }
}
